import { defineStore } from "pinia"
import {  Expert, ExpertPageResult } from "@/models/expert"
import { expertApi, tagApi } from "@/services"
import { BasicPageSearch } from "@/models/basicType"
import { toast } from "vue3-toastify"


const useExpertStore  = defineStore('Expert', {
    // state
    state:() =>({ 
        pageSize: 10,
        pageNum: 1,
        totalRecords:0,
        selectedIds:[] as number[],   //批量删除的数据
        expertResult: {} as ExpertPageResult
    }),
    // actions
    actions:{       
        //添加行家
        handleAddNew(){
            
        },
        async refreshData(){
            await this.getExpert(this.pageSize,this.pageNum)
        },
        //删除行家
        async handleDelete(id:number)
        {
            try{                
                const res = await expertApi.deleteExpertById(id)
                this.refreshData()
                toast.success("操作成功")
            }
            catch(err)
            {
                toast.error("操作失败")
            }
            
        }, 
        //批量删除
        async handleDeleteAll(){
            try{
                const res = await expertApi.deleteExpertAll(this.selectedIds)
                this.refreshData()
                toast.success("操作成功")
            }
            catch(err)
            {
                toast.error("操作失败")
            }
        },
        //上下架行家     
        async handleToggleOnSale(expert:Expert)
        {
            try{
                const res = await expertApi.toggleExpertOnSale(expert)
                this.refreshData()
                toast.success("操作成功")
            }
            catch(err)
            {
                toast.error("操作失败")
            }            
        },
        async handlePageChange(pageNum:number,pageSize:number){         
                        
            this.pageNum = pageNum
            this.pageSize = pageSize   
            this.refreshData()
        },
        // 获得行家
        async getExpert(pageSize:number,pageNum:number)
        {
            try{        
                const data : BasicPageSearch = {
                    pageSize: pageSize,
                    pageNum: pageNum,
                }
                const res = await expertApi.getExpert(data)
               
                console.log("Expert Result:",res.data)
                this.expertResult = res.data 
                this.pageNum = pageNum
                this.pageSize = pageSize  
                this.totalRecords = this.expertResult.count            
            }
            catch(err)
            {
        
            }
        },

    },
    getters:{
        ExpertSource:(state) => state.expertResult.records,
    }
})

export default useExpertStore